package com.aisino.nmg.ant.task;

import com.aisino.nmg.ant.env.Environment;
import com.aisino.nmg.ant.project.IProject;
import com.aisino.nmg.system.generator.mapper.AppConfigMapper;
import com.aisino.nmg.system.generator.mapper.ColumnConfigMapper;
import com.aisino.nmg.system.generator.mapper.TableConfigMapper;
import com.aisino.nmg.util.SpringContextUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class GeneratorToolTask extends BaseTask {
	private IProject project;
	private EnvironmentTask environmentTask;
	private List<AbstractTask> generatorTasks = new ArrayList<>();
	private AppConfigMapper appConfigMapper = null;
	private TableConfigMapper tableConfigMapper = null;
	private ColumnConfigMapper columnConfigMapper = null;

	public GeneratorToolTask(IProject project) {
		this.project = project;
		appConfigMapper = SpringContextUtil.getBean(AppConfigMapper.class);
		tableConfigMapper = SpringContextUtil.getBean(TableConfigMapper.class);
		columnConfigMapper = SpringContextUtil.getBean(ColumnConfigMapper.class);
	}

	public IProject getProject() {
		return this.project;
	}

	public AppConfigMapper getAppConfigMapper(){
		return this.appConfigMapper;
	}

	public TableConfigMapper getTableConfigMapper(){
		return this.tableConfigMapper;
	}

	public ColumnConfigMapper getColumnConfigMapper(){
		return this.columnConfigMapper;
	}

	/**
	 * 创建环境任务
	 *
	 * @return 环境任务
	 */
	public EnvironmentTask createEnvironment() {
		if (environmentTask != null) {
			throw new RuntimeException("已经存在EnvironmentTask, 不允许再进行创建");
		}
		EnvironmentTask environmentTask = new EnvironmentTask(this);
		this.environmentTask = environmentTask;

		return this.environmentTask;
	}

	/**
	 * 获取生成器的环境配置参数
	 * @return
	 */
	public Environment getEnvironment(){
		return environmentTask.getEnvironment();
	}

	public EnvironmentTask getEnvironmentTask(){
		return this.environmentTask;
	}

	public void addGeneratorTask(AbstractTask abstractTask){
		generatorTasks.add(abstractTask);
	}

	public void cleanGeneratorTask(){
		generatorTasks.clear();
	}

	@Override
	public void execute() {
		generatorTasks.sort(new Comparator<AbstractTask>() {

			@Override
			public int compare(AbstractTask o1, AbstractTask o2) {
				return o1.getSort() - o2.getSort();
			}
		});

		if(generatorTasks != null && generatorTasks.size() > 0) {
			Iterator iterator = generatorTasks.iterator();
			AbstractTask generatorTask = null;
			while (iterator.hasNext()) { // 循环执行所有生成任务
				generatorTask = (AbstractTask) iterator.next();
				generatorTask.execute();
			}
		}
	}
}
